<template>
  <div>
    <!-- 顶部 -->
    <!-- <common-header></common-header> -->
    <TopNav></TopNav>
    <!-- <Search></Search> -->

    <div class="shopDetailContain">
      <!-- <h2>商品Id为：{{shopId}}</h2> -->

      <div class="shopDeatil">
        <el-card>
          <div class="shopDetailLeft">
            <div class="pic" @mouseleave="imgshow=false">
              <img :src="imgbaseUrl+bigimg" alt />
              <div class="cover"></div>
              <transition name="el-fade-in-linear">
                <div
                  class="detail"
                  v-show="imgshow"
                  :style="{backgroundImage:'url('+imgbaseUrl+bigimg+')'}"
                ></div>
              </transition>
            </div>
            <ul class="imglist">
              <li
                v-for="(list,index) in 4"
                :key="index"
                :class="imgidx===index?'activeli':''"
                @click="changeimgli(index)"
              >
                <img
                  v-if="imgkeyarr[index]"
                  :src="imgbaseUrl +imgkeyarr[index]"
                  alt
                  @mouseenter="changeimg(index)"
                />
              </li>
            </ul>
          </div>
          <div class="shopDetailRight">
            <div class="productDetail">
              <div class="pro-name">
                <h1>{{productDetal.name}}</h1>
              </div>
              <div class="pro-price">
                <label class="prospan">价 格</label>
                <h1>￥{{productDetal.price}}</h1>
              </div>
              <div class="pro-description">
                <span class="prospan">库存</span>
                <span class="descriptionnum">{{productDetal.stock}}</span>
              </div>
              <div class="pro-choosepic">
                <span class="prospan">选择颜色</span>
                <ul>
                  <li
                    v-for="(item,index) in productColor"
                    :key="index"
                    :class="coloridx===index?'activeli':''"
                    @click="changecolorli(index)"
                  >{{item}}</li>
                </ul>
              </div>
              <div class="pro-description">
                <span class="prospan">选择版本</span>
                <ul>
                  <li
                    :class="configidx===index?'activeli':''"
                    @click="changeDes(key,index)"
                    v-for="(item,key,index) in configurationPrice"
                    :key="index"
                  >{{key}}</li>
                </ul>
              </div>
              <div class="prosubmit">
                <div class="quantity">
                  <el-button
                    type="info"
                    @click="minQuantity"
                    :disabled="mindisabled"
                    icon="el-icon-minus"
                  ></el-button>
                  <el-input
                    class="input"
                    @input="quantityInput"
                    @change="quantityChange"
                    v-model="quantity"
                  ></el-input>
                  <el-button type="info" @click="addQuantity" icon="el-icon-plus"></el-button>
                </div>
                <div class="shopcar">
                  <el-button icon="el-icon-shopping-cart-1" @click="addShopCar">加入购物车</el-button>
                </div>
                <div class="shopbuy">
                  <el-button type="primary" icon="el-icon-coin" @click="buyShop">立即购买</el-button>
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </div>
      <div class="productParam">
        <el-card>
          <div :class="['productTab',isFixed?'Fixed':'']">
            <ul>
              <li :class="activeindex===0?'active':' '" @click="scrollTo(0)">规格参数</li>
              <li :class="activeindex===1?'active':' '" @click="scrollTo(1)">售后服务</li>
              <li :class="activeindex===2?'active':' '" @click="scrollTo(2)">用户评论({{total}})</li>
            </ul>
          </div>
          <div class="product-Params">
            <div class="titlename">规格参数</div>
            <div class="key-parameter">
              <div class="Detailvideo">
                <div v-if="productDetal.videoUrl!==''&&productDetal.videoUrl!==null">
                  <video
                    width="750"
                    height="360"
                    :poster="productDetal.videoUrl+'?x-oss-process=video/snapshot,t_5000,f_jpg,w_650,h_360'"
                    :src="productDetal.videoUrl"
                    type="video/mp4"
                    id="player1"
                    controls="controls"
                    preload="none"
                  ></video>
                </div>
              </div>
              <ul>
                <li v-for="(list,index) in detailimgarr" :key="index">
                  <img :src="list" alt />
                </li>
              </ul>
            </div>
          </div>
          <div class="product-service">
            <div class="titlename">售后服务</div>
            <div class="serivcedetail">
              <p>
                <span style="color: rgb(51,51,51);">本产品不享受三包服务，售出概不负责</span>
                <br />
                <span style="color: rgb(51,51,51);">如因质量问题或性能故障，不保险</span>
                <br />
                <span style="color: rgb(51,51,51);">消费者服务热线：88888</span>
                <br />
                <span style="color: rgb(51,51,51);">官方服务软件：xxApp</span>
                <br />
                <span style="color: rgb(51,51,51);">
                  有问题点击查询：
                  <a href="https://baidu.com/">https://baidu.com/</a>
                </span>
              </p>
              <ul>
                <li>*因可能存在系统缓存，页面更新导致价格变动异常等不确定性情况出现，如您发现活动商品标价或促销信息有异常，请您立即联系我们，以便我们及时补正。</li>
                <li>*以上页面中的产品图片及屏幕内容仅作示意，实物产品效果（包括但不限于外观、颜色、尺寸）和屏幕显示内容（包括但不限于背景、UI、配图）可能略有差异，请以实物为准。</li>
                <li>*以上页面中的数据为理论值，实际使用中可能因产品个体差异、软件版本、使用条件和环境因素不同略有不同，请以实际使用的情况为准。</li>
              </ul>
            </div>
          </div>
          <div class="product-comment">
            <div class="titlename">用户评论</div>
            <!-- 分页显示评论 -->
            <div class="commentdetail">
              <ul>
                <li class="detail" v-for="(item, index) in commentDetail" :key="index">
                  <div class="userimg">
                    <el-avatar
                      :size="75"
                      src="https://res.vmallres.com/rms/comment/image/U0392/FB01813CA1E61CA89CC6C2ACB9A2D3EADDFEDEC06113E500DF7FCA8219771C5D/e259ec4b783b41590fe07e5a.jpg"
                    ></el-avatar>
                    <span>{{item.username}}</span>
                  </div>
                  <div class="usercomdetail">
                    <div class="userrate">
                      <!-- <el-rate v-model="userrate" :colors="colors"></el-rate> -->
                      <span class="usercomtime">{{item.createTime}}</span>
                    </div>
                    <div class="usermsg">{{item.content}}</div>
                    <div class="usercomimg">
                      <div class="imgli" v-for="(img,index) in item.imageUrl" :key="index">
                        <img :src="imgbaseUrl+img" alt />
                      </div>
                    </div>
                    <div class="userproduct">{{item.productName}}</div>
                  </div>
                </li>
              </ul>
            </div>
          </div>
          <div class="pagination">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="commentPage.pageNum"
              :page-sizes="[5,10,30]"
              :page-size="commentPage.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
            ></el-pagination>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 底部 -->
    <common-footer></common-footer>
  </div>
</template>

<script>
// import CommonHeader from '../../components/Show/CommonHeader'
import CommonFooter from "../../components/Show/CommonFooter";
// import Search from "../../components/Show/Search";
import TopNav from "../../components/Show/TopNav";
// import CommonHeader from "../../components/Show/Search";
import { mapState } from "vuex";
export default {
  components: {
    // CommonHeader,
    CommonFooter,
    // Search,
    TopNav,
  },
  data() {
    return {
      imgbaseUrl: "https://phone-shop.oss-cn-beijing.aliyuncs.com/",
      bigimg: "",

      smallimg: [],
      imgshow: false,
      configurationPrice: "",
      productColor: "",
      price: "",
      //数量
      quantity: 1,
      mindisabled: true,
      activeindex: 0,
      // 图片选中
      imgidx: 0,
      coloridx: 0,
      configidx: 0,
      userrate: null,
      colors: ["#99A9BF", "#F7BA2A", "#FF9900"],
      isFixed: false,
      imgkeyarr: [],
      detailimgarr: [],
      total: 0,

      // 商品信息
      productDetal: {},
      // 评论信息
      commentDetail: {},

      commentPage: {
        pageNum: 1,
        pageSize: 5,
      },
    };
  },
  methods: {
    changeimg(index) {
      this.bigimg = this.imgkeyarr[index];
    },
    changeimgli(index) {
      this.imgidx = index;
    },
    changecolorli(index) {
      this.coloridx = index;
      console.log(index);
    },
    quantityInput() {
      if (this.quantity > this.productDetal.stock) {
        this.quantity = this.productDetal.stock;
        this.$message.info("不能超过当前库存");
      }
      if (isNaN(this.quantity)) {
        this.quantity = 1;
      }
      if (this.quantity > 1) {
        this.mindisabled = false;
      } else {
        this.mindisabled = true;
      }
    },
    quantityChange() {
      if (this.quantity == "" || this.quantity == 0) {
        this.quantity = 1;
      }
      if (this.quantity > 1) {
        this.mindisabled = false;
      } else {
        this.mindisabled = true;
      }
      console.log(this.quantity);
    },
    addQuantity() {
      this.mindisabled = false;
      if (this.quantity < this.productDetal.stock) {
        this.quantity++;
      }
    },
    minQuantity() {
      if (this.quantity > 1) {
        this.quantity--;
      } else {
        this.mindisabled = true;
      }
    },
    // 加入购物车
    async addShopCar() {
      let isLogin = window.sessionStorage.getItem("userInfo");
      if (!isLogin) {
        this.$message.info("您未登录，两秒后为你跳转至登录页");
        setTimeout(() => {
          return this.$router.push("/login");
        }, 2000);
      }
      // console.log("用户id：", this.userInfo.id);
      // console.log("商品id：", this.shopId);
      // console.log("数量：", this.quantity);
      let param = {
        userId: this.userInfo.id,
        productId: parseInt(this.shopId),
        quantity: this.quantity,
        checked: 0,
      };

      const { data: res } = await this.$http.post("/cart/add", param);
      if (res.code !== 200) {
        return this.$message.danger("添加购物车失败");
      }
      this.$notify({
        // title: '成功',
        message: "添加购物车成功",
        type: "success",
        duration: 2000,
      });
    },
    onScroll() {
      const scrollTop =
        document.documentElement.scrollTop || document.body.scrollTop;
      //   console.log(scrollTop);
      const productParams = document.querySelector(".product-Params").offsetTop;
      const productservice =
        document.querySelector(".product-service").offsetTop - 60;
      const productcomment =
        document.querySelector(".product-comment").offsetTop - 60;

      //   console.log(ProTab);
      if (scrollTop >= productParams) {
        this.activeindex = 0;
        this.isFixed = true;
        if (scrollTop >= productservice) {
          this.activeindex = 1;
        }
        if (scrollTop >= productcomment) {
          this.activeindex = 2;
        }
      } else {
        this.isFixed = false;
      }
    },
    scrollTo(idx) {
      //   console.log(scrollTop);
      const productParams =
        document.querySelector(".product-Params").offsetTop - 40;
      const productservice =
        document.querySelector(".product-service").offsetTop - 60;
      const productcomment =
        document.querySelector(".product-comment").offsetTop - 60;
      if (idx === 0) {
        document.documentElement.scrollTop = productParams;
        this.activeindex = 0;
      }
      if (idx === 1) {
        document.documentElement.scrollTop = productservice;
        this.activeindex = 1;
      }
      if (idx === 2) {
        document.documentElement.scrollTop = productcomment;
        this.activeindex = 2;
      }
    },
    // 获取商品详情
    async getDetail() {
      const { data: res } = await this.$http.get(
        `product/detail/${this.shopId}`
      );
      fetch("http://121.5.221.199:8080/back/product/product-item/2300", {
        method: "get",
      })
        .then((response) => response.json())
        .then((data) => {
          console.log(this);
          let color = data.data.colors;
          data.data.configurationPrice = JSON.parse(
            data.data.configurationPrice
          );
          this.configurationPrice = data.data.configurationPrice;
          for (const key in this.configurationPrice) {
            this.price = this.configurationPrice[key];
            this.price = this.price.toFixed(2);
            // console.log(this.configurationPrice[key]);
            break;
          }
          color = color.split(",");
          this.productColor = color;
          console.log("productColor", this.productColor);
          console.log("data:", data);
        });
      if (res.code !== 200) {
        return this.$message.danger("获取数据失败");
      }
      console.log(res.data.product);
      let img = JSON.parse(res.data.product.mainImageUrl);
      this.smallimg = img;
      for (const key in img) {
        this.imgkeyarr.push(key);
      }
      this.imgkeyarr = this.imgkeyarr.map((item) => {
        item = this.smallimg[item];
        return item;
      });
      this.productDetal = res.data.product;
      if (res.data.product.videoUrl) {
        this.productDetal.videoUrl =
          this.imgbaseUrl + this.productDetal.videoUrl;
      }

      // console.log(this.imgkeyarr);
      this.bigimg = this.imgkeyarr[0];

      let detailimg = JSON.parse(res.data.product.detail);
      for (const key in detailimg) {
        this.detailimgarr.push(key);
      }
      this.detailimgarr = this.detailimgarr.map((item) => {
        item = this.imgbaseUrl + detailimg[item];
        return item;
      });
      console.log(this.detailimgarr);

      // console.log(this.productDetal);
      // console.log(this.shopId);
    },
    // 获取商品评论
    async getComment() {
      const { data: res } = await this.$http.get(
        `comment/searchAll?pageNum=${this.commentPage.pageNum}&pageSize=${this.commentPage.pageSize}`
      );
      // const { data: res } = await this.$http.get(
      //   "comment/searchAll",{params:this.commentPage}
      // );
      if (res.code !== 200) {
        return this.$message.danger("获取评论失败");
      }
      console.log("评论res", res);
      this.commentDetail = res.data;
      this.total = res.extraData.total;
      this.commentDetail = this.commentDetail.map((item) => {
        item.imageUrl = JSON.parse(item.imageUrl);
        item.createTime = this.timeStamp2String(item.createTime);
        return item;
      });
      console.log("评论", this.commentDetail);
    },
    changeDes(key, index) {
      this.configidx = index;

      this.price = this.configurationPrice[key];
      // console.log(this.configurationPrice[key]);
      // console.log(key);
    },
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`)
      this.commentPage.pageSize = val;
      this.getComment();
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`)
      this.commentPage.pageNum = val;
      this.getComment();
    },
    async buyShop() {
      let isLogin = window.sessionStorage.getItem("userInfo");
      if (!isLogin) {
        this.$message.info("您未登录，两秒后为你跳转至登录页");
        setTimeout(() => {
          return this.$router.push("/login");
        }, 2000);
      } else {
        let shoplist = [
          {
            productId: this.shopId,
            productName: this.productDetal.name,
            productImage: this.imgkeyarr[0],
            currentUnitPrice: this.price,
            quantity: this.quantity,
            totalPrice: (this.price * this.quantity).toFixed(2),
          },
        ];

        this.$store.commit("setOrderItem", shoplist);
        window.sessionStorage.setItem("shoplist", JSON.stringify(shoplist));
        // console.log("选中的商品",this.orderItemList);
        this.$router.push({ path: `/shopOrder/${this.shopId}` });
      }
      // const { data: res } = await this.$http.get("/order/getOrderNumber");
      // if (res.code !== 200) {
      //   return this.$message.danger("购买失败，请重新登录")
      // }
      // console.log(res.data);
      // console.log(this.price);
    },
    timeStamp2String(time) {
      var dateee = time;
      console.log(dateee);
      var date = new Date(+new Date(dateee) + 16 * 3600 * 1000)
        .toISOString()
        .replace(/T/g, " ")
        .replace(/\.[\d]{3}Z/, "");
      return date;
    },
  },
  computed: {
    shopId() {
      return this.$route.params.id; // 获取路径上的id
    },
    ...mapState({
      userInfo: (state) => state.user.userInfo,
      orderItemList: (state) => state.shopSelect.orderItemList,
    }),
  },
  created() {
    this.getDetail();
    this.getComment();
  },
  mounted() {
    // 放大镜实现
    var pic = document.querySelector(".shopDetailLeft .pic");
    var detail = document.querySelector(".shopDetailLeft .detail");
    var cover = document.querySelector(".cover");
    // 监听鼠标移动
    pic.addEventListener("mousemove", (e) => {
      //   console.log(e);
      this.imgshow = true;
      var x = e.clientX,
        y = e.clientY,
        cx = pic.getBoundingClientRect().left,
        cy = pic.getBoundingClientRect().top;
      var tx = x - cx - 50;
      var ty = y - cy - 50;
      if (tx < 0) {
        tx = 0;
      }
      if (ty < 0) {
        ty = 0;
      }
      if (tx > 400 - 100) {
        tx = 300;
      }
      if (ty > 400 - 100) {
        ty = 300;
      }
      detail.style.backgroundPosition =
        (tx / 300) * 100 + "%" + (ty / 300) * 100 + "%";
      cover.style.left = tx + "px";
      cover.style.top = ty + "px";
    });
    window.addEventListener("scroll", this.onScroll);
  },
  destroyed() {
    window.removeEventListener("scroll", this.onScroll);
  },
};
</script>

<style lang="less" scoped>
.shopDetailContain {
  min-width: 1200px;
  min-height: 550px;
  background-color: #f8f8f8;
  padding: 20px 0;
  .shopDeatil {
    width: 1200px;
    margin: 0 auto;
    height: 100%;
    .shopDetailLeft {
      height: 600px;
      width: 450px;
      float: left;
      .pic:hover {
        cursor: pointer;
      }
      .pic {
        position: relative;
        width: 90%;
        margin: auto;
        // margin-bottom: 10px;
        img {
          display: block;
          width: 400px;
          height: 400px;
        }
        .cover {
          width: 100px;
          height: 100px;
          position: absolute;
          left: 0;
          top: 0;
          opacity: 0.5;
          background-image: url("../../assets/images/shop/cover.jpg");
        }
        .detail {
          position: absolute;
          display: block;
          left: 420px;
          top: 0px;
          width: 400px;
          height: 400px;
          z-index: 999;
          border: 3px solid #ccc;
          background-repeat: no-repeat;
          /* 400/100 = 4倍 */
          background-size: 400%;
        }
      }
      .imglist {
        padding: 0;
        width: 90%;
        list-style: none;
        display: flex;
        margin: 20px auto;
        li {
          // padding: 5px;
          margin-left: 5px;
        }
        li:nth-child(1) {
          margin: 0;
        }
        li:hover {
          border: 1px solid #ca141d;
          cursor: pointer;
        }
        img {
          display: block;
          width: 88px;
          height: 88px;
        }
      }
    }
    .shopDetailRight {
      width: 620px;
      //   border: 1px solid red;
      //   height: 400px;
      float: left;
      margin-left: 60px;
      margin-bottom: 20px;
      .productDetail {
        .pro-name {
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          word-break: break-all;
          -webkit-box-orient: vertical;
          h1 {
            //   text-indent: 1em;
            margin: 0;
            display: block;
            font-size: 1.3em;
          }
        }
        .pro-price {
          margin-top: 20px;
          display: flex;
          align-items: center;
          //   font-size: 25px;

          h1 {
            margin-left: 10px;
            font-size: 1.5em;
            color: #f96;
          }
        }
        .pro-description {
          .descriptionnum {
            margin-left: 10px;
            font-size: 20px;
          }
        }
        .pro-choosepic,
        .pro-description {
          display: flex;
          align-items: center;
          margin-top: 10px;
          ul {
            display: flex;
            flex: 1;
            flex-wrap: wrap;
            li {
              margin-top: 5px;
              // width: 86px;
              padding: 0 10px;
              line-height: 33px;
              text-align: center;
              background-color: #fff;
              color: #000;
              border: 1px solid #717171;
              margin-left: 11px;
              border-radius: 5px;
            }
            // li:nth-child(1) {
            //   background-color: #fff;
            //   color: #f75e04;
            //   border: 1px solid #f75e04;
            // }
            // li:hover {
            //   cursor: pointer;
            // }
            li:hover {
              border: 1px solid #ff6700;
              color: #ff6700;
              cursor: pointer;
            }
            .activeli {
              border: 1px solid #ff6700;
              color: #ff6700;
            }
          }
        }
        .prosubmit {
          margin-top: 30px;
          display: flex;
          .el-button {
            font-size: 20px;
            border: none;
            color: #fde1ff;
          }
          .quantity {
            display: flex;
            width: 200px;
            align-items: center;
            .input /deep/.el-input__inner {
              text-align: center;
              font-size: 20px;
              line-height: 45px;
              height: 45px;
            }
          }
          .shopcar,
          .shopbuy {
            margin-left: 10px;
            // display: flex;
            justify-content: center;
            // flex:1;
            .el-button {
              background-color: #f75e04;
            }
          }
          .shopbuy {
            .el-button {
              background-color: #f1464f;
            }
          }

          // .shopbuy {
          //   margin-left: 20px;
          //   display: flex;
          //   flex: 1;
          //   .el-button {
          //     background-color: #e83030;
          //   }
          // }
        }
      }
    }
  }

  .productParam {
    width: 1200px;
    margin: 0 auto;
    height: 100%;
    margin-top: 20px;
    .productTab {
      ul {
        display: flex;
        justify-content: center;
        li {
          margin-right: 25px;
          color: #a4a4a4;
          font-size: 20px;
        }
        li:hover {
          cursor: pointer;
        }
        .active {
          color: #ca141d;
          border-bottom: 3px solid #ca141d;
        }
      }
    }
    .product-Params {
      margin-top: 30px;
      .key-parameter {
        margin-top: 10px;
        padding: 20px 0 0 20px;
        display: flex;
        flex-direction: column;
        align-items: center;
        ul {
          margin-top: 70px;
        }

        // ul {
        //   margin-left: 80px;
        //   li {
        //     label {
        //       min-width: 200px;
        //       //  border: 1px solid blue;
        //     }
        //   }
        // }
      }
    }
    .product-service {
      margin-top: 30px;
      .serivcedetail {
        margin-top: 10px;
        padding: 20px 0 0 20px;
        border-top: 2px solid #eee;
      }
    }
    .product-comment {
      margin-top: 30px;
      .commentdetail {
        margin-top: 10px;
        padding-top: 20px;
        border-top: 2px solid #eee;
        .detail {
          display: flex;
          margin-bottom: 20px;
          padding-bottom: 4px;
          border-bottom: 1px solid #ccc;
          .userimg {
            width: 130px;
            padding: 10px 10px 0 20px;
            font-size: 0.6em;
            display: flex;
            align-items: center;
            word-break: break-all;
            flex-direction: column;
          }
          .usercomdetail {
            flex: 1;
            .userrate {
              display: flex;
              justify-content: space-between;
              padding-right: 10px;
              .usercomtime {
                color: #ccc;
              }
            }
            .usermsg {
              margin-top: 5px;
              font-size: 14px;
            }
            .usercomimg {
              margin-top: 15px;
              display: flex;
              flex-wrap: wrap;
              img {
                border: 1px solid #eee;
                display: block;
                width: 100px;
                height: 100px;
              }
              .imgli {
                margin-left: 5px;
              }

              .imgli:nth-child(1) {
                margin: 0;
              }
            }
            .userproduct {
              margin-top: 15px;
              font-size: 13px;
              color: #ccc;
            }
          }
        }
        .detail:last-child {
          border-bottom: none;
        }
      }
    }
  }
}
// 选中时样式
.activeli {
  border: 1px solid #ff6700;
  color: #ff6700;
}
.Fixed {
  position: fixed;
  top: 0;
  background-color: white;
  width: 1160px;
  z-index: 10px;
  // line-height: 40px;
  // padding-bottom: 10px;
  // padding: 10px;
}
.titlename {
  font-size: 20px;
  padding-left: 15px;
  border-left: 3px solid red;
}
.prospan {
  display: inline-block;
  width: 85px;
  margin-top: 5px;
  text-indent: 10px;
  line-height: 30px;
}
ul {
  margin: 0;
  padding: 0;
  list-style: none;
}
</style>